package com.william.springsecurity.handler;

import cn.hutool.json.JSONUtil;
import com.william.springsecurity.common.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// 登录失败处理类
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter out = httpServletResponse.getWriter();
        Result loginFailed = Result.failed(HttpServletResponse.SC_BAD_REQUEST,e.getMessage());
        out.write(JSONUtil.toJsonStr(loginFailed));
        out.flush();
        out.close();
    }
}
